import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers.Authorization = store.getters.token
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { code, msg, data, token } = response.data

    if (code === 200) {
      msg && Message.success(msg)
      token && store.commit('user/SET_TOKEN', token)
      return data
    } else if (code === 401) {
      store.dispatch('user/logout')
      return Promise.reject()
    } else {
      msg && Message.error(msg)
      return Promise.reject()
    }
  },
  error => {
    // console.dir(error)
    const { message } = error
    if (message === 'Network Error') {
      Message.error('网络异常，请稍后再试！')
    } else if (message === 'timeout of 1ms exceeded') {
      Message.error('网络异常，请稍后再试！')
    } else {
      Message.error('网络异常，请稍后再试！')
    }
    return Promise.reject()
  }
)

export default service
